<template>
	<view class="page__content">
		<!-- 顶部导航 -->
		<up-navbar :fixed="false" :autoBack="false" :safeAreaInsetTop="true">
			<template #left>
				<text class="navbar-title">汇创云 QMS</text>
			</template>
		</up-navbar>

		<view class="page__content__main">

			<!-- 📊 统计数据 -->
			<view class="common-card">
				<view class="common-card__header">
					<text class="card-title">统计数据</text>
				</view>

				<view class="common-card__body x-bc">
					<view class="charts-box">
						<qiun-data-charts type="ring" :opts="chartsConfig.opts" :chartData="chartsConfig.chartData" />
					</view>

					<view class="charts-info">
						<uni-row class="stats-grid">
							<uni-col v-for="(v, key) in stats" :key="key" :span="12" class="stats-item">
								<view>
									<text class="stats-value" :style="{ color: v.color }">{{ v.value }}</text>
									<text class="stats-label">{{ v.name }}</text>
								</view>
							</uni-col>
						</uni-row>
					</view>
				</view>
			</view>

			<!-- 🧩 检验类型 -->
			<view class="common-card">
				<view class="common-card__header">
					<text class="card-title">检验类型</text>
				</view>

				<view class="common-card__body">
					<u-grid :border="false" col="4" class="inspect-grid">
						<u-grid-item v-for="(item, index) in UsualModules" :key="index" @click="handleModuleClick(item)"
							class="inspect-item">
							<view class="icon-wrapper"
								:style="{ background: `linear-gradient(135deg, ${item.AP_Colour}20, ${item.AP_Colour}05)` }">
								<uni-icons fontFamily="CustomFontPlatform" :color="item.AP_Colour" :size="42">
									{{ uni.$utils.toUniCode(item.PIC_PH) }}
								</uni-icons>
							</view>
							<text class="grid-text">{{ item.APFunName }}</text>
						</u-grid-item>
					</u-grid>
				</view>
			</view>

			<!-- 📑 检验单据 -->
			<view class="common-card">
				<view class="common-card__header">
					<text class="card-title">检验单据</text>
				</view>

				<view v-if="orderList.length === 0" class="empty">
					暂无检验单据
				</view>

				<view v-else class="common-card__body">
					<view v-for="(item, index) in orderList" :key="item.id || index" class="doc-card">
						<!-- 顶部：类型 + 状态 -->
						<view class="doc-header">
							<text class="type-tag">{{ item.typeName }}</text>
							<view class="doc-status-row">
								<view class="tag status">{{ item.status }}</view>
								<view :class="['tag', 'result', getResultClass(item.result)]">{{ item.result }}</view>
								<view class="tag approve">{{ item.approve }}</view>
							</view>
						</view>

						<!-- 单号 -->
						<text class="bill-no">{{ item.no }}</text>

						<!-- 产品信息 -->
						<view class="doc-body">
							<text>产品：{{ item.product }}</text>
							<text>批次：{{ item.batch }}</text>
							<text>数量：{{ item.qty }}</text>
							<text>合格：{{ item.qualified }}</text>
							<text>不合格：{{ item.unqualified }}</text>
						</view>

						<!-- 日期 -->
						<view class="doc-footer">
							<text class="date">{{ item.date }}</text>
						</view>
					</view>
				</view>
			</view>

		</view>
	</view>
</template>


<script setup lang="ts" name="page-index">
	import { reactive, ref } from 'vue';
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { useMainStore, useQmsStore, usePermissionStore, useUserStore } from '@/store';
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';

	// ---------- Store 实例 ----------
	const qmsStore = useQmsStore()
	const mainStore = useMainStore()
	const permissionStore = usePermissionStore()
	const userStore = useUserStore()

	// ---------- 请求方法 ----------
	const { request } = useRequestQueue()

	// ---------- 图表配置 ----------
	interface ChartInfo {
		WJYSL : number
		JYSL : number
		HGNumber : number
		BHGNumber : number
	}

	const chartsConfig = reactive({
		opts: {
			rotate: false,
			rotateLock: false,
			color: ['#FAC858', '#52aeff', '#91CB74', '#fa231b', '#999999', '#73C0DE', '#3CA272', '#FC8452', '#9A60B4', '#ea7ccc'],
			padding: [0, 0, 0, 0],
			dataLabel: false,
			enableScroll: false,
			legend: {
				show: false,
				position: 'right',
				lineHeight: 10
			},
			title: {
				name: '检验数据',
				fontSize: 15,
				color: '#666'
			},
			subtitle: {
				name: '',
				fontSize: 25,
				color: '#7cb5ec'
			},
			extra: {
				ring: {
					ringWidth: 30,
					activeOpacity: 0.5,
					activeRadius: 10,
					offsetAngle: 0,
					labelWidth: 0,
					border: true,
					borderWidth: 2,
					borderColor: '#fff'
				}
			}
		},
		chartData: {},
		chartDataInfo: {} as ChartInfo
	})

	// ---------- 检验类型 ----------
	const UsualModules = ref<any[]>([])
	const typeNameMap = reactive<Record<string, string>>({})

	// ---------- 检验单据 ----------
	const orderList = ref<any[]>([])

	// ---------- 权限模块 ----------
	const moduleInfoAll = permissionStore.moduleInfoAll
	const moduleInfoAll_filter = moduleInfoAll[0].Node.filter((item : any) => !item.IsTabbar)

	// =====================
	// 获取检验类型映射
	// =====================
	const getTypeMap = async () => {
		const ret = await request({
			url: 'Get_QMS_FType',
			method: 'POST',
			data: {}
		})

		if (ret.status === 200) {
			ret.data.ds.forEach((item : any) => {
				typeNameMap[item.FType] = item.Name
			})
		}
	}

	// =====================
	// 获取统计图表数据
	// =====================
	let stats = ref<any>([]);
	const getPageInit = async () => {
		const ret = await request({
			url: 'APP_SYJK',
			method: 'POST',
			data: {}
		})

		if (ret.status === 200) {
			const obj = ret.data.ds[0] || {}
			obj.WJYSL = obj.WJYSL || 0

			chartsConfig.chartDataInfo = obj;

			stats.value = [
				{ name: '未检验数', value: uni.$utils.formatPrice(obj.WJYSL), color: "#FAC858" },
				{ name: '已检验数', value: uni.$utils.formatPrice(obj.JYSL), color: "#52aeff" },
				{ name: '合格数', value: uni.$utils.formatPrice(obj.HGNumber), color: "#91CB74" },
				{ name: '不合格数', value: uni.$utils.formatPrice(obj.BHGNumber), color: "#fa231b" },
			]


			chartsConfig.chartData = {
				series: [
					{
						data: [
							{ name: '未检验数', value: obj.WJYSL },
							{ name: '已检验数', value: obj.JYSL },
							{ name: '合格数', value: obj.HGNumber },
							{ name: '不合格数', value: obj.BHGNumber }
						]
					}
				]
			}
		}
	}

	// =====================
	// 初始化常用检验模块
	// =====================
	const initUsualModules = () => {
		UsualModules.value = moduleInfoAll
			.flatMap((item : any) => item.Node.filter((row : any) => !row.IsTabbar))
			.sort((a : any, b : any) => a.APFunCode - b.APFunCode)
			.slice(0, 4)
	}

	// =====================
	// 获取检验单据列表
	// =====================
	const getOrderList = async () => {
		const ret = await request({
			url: 'APP_SYJYSJJK',
			method: 'POST',
			data: {}
		})

		if (ret.status === 200) {
			const { ds, ds1, ds2, ds3, ds4 } = ret.data

			// 标准化
			const normalizeList = (list : any[]) =>
				(list || []).map(item => ({
					id:
						item.InspectionSheetID ||
						item.FirstInspectionID ||
						item.TourInspectionID ||
						item.FinalInspectionID ||
						item.FinishedInspectionID,
					typeCode: item.FType,
					typeName: typeNameMap[item.FType] || '未知类型',
					status: item.SFJYName,
					approve: item.ApproveName,
					date: item.BillDate,
					no: item.BillNO,
					product: item.ProductName,
					batch: item.Fbatch,
					qty: item.BJNum,
					qualified: item.HGNumber ?? 0,
					unqualified: item.BHGNumber ?? 0,
					result: item.Result1
				}))

			// 合并所有数据
			const allDocs = [
				...normalizeList(ds),
				...normalizeList(ds1),
				...normalizeList(ds2),
				...normalizeList(ds3),
				...normalizeList(ds4)
			]

			// 权限过滤
			orderList.value = allDocs.filter((item : any) =>
				moduleInfoAll_filter.some((row : any) => row.APFunName === typeNameMap[item.typeCode])
			)

			// 按日期倒序
			// orderList.value.sort((a, b) => new Date(b.date) - new Date(a.date))
		}
	}

	// =====================
	// 辅助：结果样式映射
	// =====================
	const getResultClass = (result : string) => {
		if (result === '合格') return 'success'
		if (result === '不合格') return 'fail'
		return 'pending'
	}

	// =====================
	// 点击模块卡片
	// =====================
	const handleModuleClick = (module : any) => {
		qmsStore.orderConfig.order_info = module
		uni.hideToast()

		const navigate = (url : string) => setTimeout(() => uni.navigateTo({ url }), 300)
		const mapPath = uni.$utils.replaceDispatchPath(module.AP_Link)

		if (mapPath.includes('.html')) {
			plus.screen.lockOrientation('landscape-primary')
			navigate('/st_qms/page_webview/webview_basic')
		} else {
			navigate(mapPath)
		}
	}

	// =====================
	// 打开统计面板
	// =====================
	const openStatBoard = () => {
		uni.navigateTo({
			url: '/st_qms/page_index/kanban/stat_dashboard'
		})
	}

	// =====================
	// 页面生命周期
	// =====================
	onLoad(async () => {
		await getTypeMap()
		await getPageInit()
		await initUsualModules()
		await getOrderList()
	})
</script>


<style lang="scss">
	.page__content {
		height: 100%;
		background-image: linear-gradient(to bottom, rgba(81, 208, 208, 1), rgba(81, 208, 208, 0.7) 40%, #fff);

		.navbar-title {
			font-size: 26rpx;
			color: #fff;
			font-weight: 600;
		}

		&__main {
			padding: 15rpx;

			.common-card {
				background-color: #fff;
				border-radius: 24rpx;
				padding: 24rpx;
				margin-bottom: 24rpx;
				box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.04);

				&__header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 12rpx;

					.card-title {
						font-size: 26rpx;
						color: #333;
						font-weight: 600;
					}
				}

				&__body {
					margin-top: 8rpx;
					width: 100%;
				}
			}

			/* --- 统计区 --- */
			.charts-box {
				width: 380rpx;
				height: 200px;
			}

			.stats-item {
				text-align: center;
				margin-top: 12rpx;

				.stats-value {
					display: block;
					font-size: 32rpx;
					font-weight: 600;
				}

				.stats-label {
					margin-top: 8rpx;
					font-size: 22rpx;
					color: #999;
				}
			}

			/* --- 检验类型 --- */
			.inspect-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 16rpx 0;
				transition: transform 0.15s ease;

				&:active {
					transform: scale(0.96);
				}

				.icon-wrapper {
					width: 100rpx;
					height: 100rpx;
					border-radius: 20%;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-bottom: 10rpx;
					box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
				}

				.grid-text {
					font-size: 24rpx;
					color: #333;
					font-weight: 500;
				}
			}

			/* --- 检验单据 --- */
			.doc-card {
				padding: 20rpx;
				border-radius: 20rpx;
				background-color: #f5f7fb;
				margin-top: 20rpx;

				.doc-header {
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-bottom: 12rpx;

					.type-tag {
						background-color: #eef4ff;
						color: #2b7bff;
						font-size: 24rpx;
						padding: 4rpx 12rpx;
						border-radius: 8rpx;
					}
				}

				.bill-no {
					font-size: 26rpx;
					color: #555;
					font-weight: 500;
					margin-bottom: 10rpx;
				}

				.doc-status-row {
					display: flex;
					align-items: center;
					gap: 12rpx;
					margin-bottom: 12rpx;

					.tag {
						padding: 4rpx 14rpx;
						font-size: 22rpx;
						border-radius: 20rpx;
						font-weight: 500;
					}

					.status {
						background-color: #eaf2ff;
						color: #2b7bff;
					}

					.approve {
						background-color: #f5f5f5;
						color: #999;
					}

					.result.success {
						background-color: #e7f8f0;
						color: #2eb872;
					}

					.result.fail {
						background-color: #ffeaea;
						color: #ff4d4f;
					}

					.result.pending {
						background-color: #fff6e6;
						color: #faad14;
					}
				}

				.doc-body {
					display: flex;
					flex-wrap: wrap;
					gap: 12rpx 30rpx;
					font-size: 24rpx;
					color: #555;
					line-height: 1.8;
				}

				.doc-footer {
					text-align: right;
					font-size: 22rpx;
					color: #999;
					margin-top: 10rpx;
				}
			}
		}
	}
</style>